import axios from 'axios'
import { ElMessage } from 'element-plus'
// import qs from "qs";
// const baseURL = import.meta.env.VITE_APP_BASE_APIAUTH;
const baseURL = '';

// 创建 axios 实例
const service = axios.create({
  baseURL:baseURL,
  timeout: 50000,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  // paramsSerializer: (params) => {
  //   return qs.stringify(params)
  // }
})

let token = localStorage.getItem('token')
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const accessToken = token
    if (accessToken) {
      config.headers.Authorization = accessToken
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
    if (
      response.config.responseType === 'blob' ||
      response.config.responseType === 'arraybuffer'
    ) {
      return response
    }    
    const { status, statusText } = response
    if (status === 200) {    
      return response.data
    }
    ElMessage.error(statusText || '系统出错')
    return Promise.reject(new Error(statusText || 'Error'))
  },
  (error) => {
    // 异常处理
    if (error.response.data) {
      const { code, msg } = error.response.data
      if (code === 'A0230') {
        ElMessage.error('您的会话已过期，请重新登录')
        // useUserStoreHook()
        //   .resetToken()
        //   .then(() => {
        //     location.reload()
        //   })
        localStorage.removeItem('loginUser')
        localStorage.removeItem('token')
        token = null
        window.location.href = '#/login'
      } else {
        ElMessage.error(msg || '系统出错')
      }
    }
    return Promise.reject(error.message)
  }
)

// 导出 axios 实例
export default service
